package com.loadmore.common.module.reply

import android.content.Context
import android.widget.Toast
import com.loadmore.common.R
import com.loadmore.common.base.BaseAdapter
import com.loadmore.common.base.RVBaseHolder
import com.loadmore.common.constants.Api
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.model.Like
import com.loadmore.common.model.Reply
import com.loadmore.common.net.Request
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.variables.Variables
import com.lzy.okgo.model.Response

/**
 * @author sunleilei
 * @date 2018/7/19
 * @time 11:10
 */
class ReplyAdapter(context: Context) : BaseAdapter(context) {

    override fun getLayoutId(): Int {
        return R.layout.layout_reply_item
    }

    override fun onBindViewHolder(holder: RVBaseHolder<*>, position: Int) {
        val topic = getItem(position) as Reply
        holder.setText(R.id.reply_content, topic.content)
                .setText(R.id.user_name,topic?.user?.name)
                .setText(R.id.like_count,"12")
                .setImage(context, R.id.user_icon, topic?.user?.getAvatar())

        holder.getText(R.id.icon_like).setOnClickListener {
            if (topic.isLike) {
                unLike(topic.id)
            }else {
                like(topic.id)
            }
            topic.isLike = !topic.isLike
        }
    }

    private fun like(id:Long) {
        var params:HashMap<String,Any> = hashMapOf()
        params.put("post_id",id)
        params.put("token", Variables.token!!)
        Request.post(Api.like,params,object : JsonCallback<BaseResponse<Like>>() {
            override fun onSuccess(response: Response<BaseResponse<Like>>?) {
                Toast.makeText(context,"like success",Toast.LENGTH_SHORT).show()
            }

            override fun onError(response: Response<BaseResponse<Like>>?) {
                super.onError(response)
            }

        })
    }

    private fun unLike(id:Long) {
        var params:HashMap<String,Any> = hashMapOf()
        params.put("post_id",id)
        params.put("token", Variables.token!!)
        Request.delete(Api.like,params,object : JsonCallback<BaseResponse<Like>>() {
            override fun onSuccess(response: Response<BaseResponse<Like>>?) {
                Toast.makeText(context,"unlike success",Toast.LENGTH_SHORT).show()
            }

            override fun onError(response: Response<BaseResponse<Like>>?) {
                super.onError(response)
            }

        })
    }
}
